package com.fzj.example.io;

import java.io.*;

/**
 * ClassName: FileWriteRead
 * date: 2019/11/7 16:20
 * Description: TODO
 * 读取行之后，拼接，容易忘记源文件的换行符问题
 * @author fanzj@bonree.com
 * @since JDK 1.8
 */
public class FileWriteReadDemo {
    public static void main(String[] args) throws IOException {
        //默认都是false，设置成true
        FileWriter writer=new FileWriter(new File("").getAbsolutePath()+File.separator+"io"+File.separator+"test.txt",true);
        writer.write("Hello，world！\n欢迎\r\n");
        writer.append("追加一行内容");
        writer.append(null);
        writer.flush();
        writer.close();
        //非追加模式，默认也是false
        FileWriter writer2=new FileWriter(new File("").getAbsolutePath()+File.separator+"io"+File.separator+"test2.txt",false);
        writer2.write("Hello，world！\n欢迎\n");
        writer2.append("并不是追加一行内容");
        writer2.append(null);
        writer2.flush();
        writer2.close();
        //缓冲区读法
        FileReader reader=new FileReader(new File("").getAbsolutePath()+File.separator+"io"+File.separator+"test.txt");
        BufferedReader bufferedReader=new BufferedReader(reader);
        String readLine;
        StringBuilder stringBuilder=new StringBuilder();
        while ((readLine=bufferedReader.readLine())!=null){
            stringBuilder.append(readLine+"\n");
        }
        System.out.println(stringBuilder.toString());
        //先关闭处理流，再关闭节点流，其实节点流可以不用关闭，源代码中会去关闭节点流
        bufferedReader.close();
        reader.close();
        //缓冲区
        FileReader reader2=new FileReader(new File("").getAbsolutePath()+File.separator+"io"+File.separator+"test2.txt");
        int readCharInt;
        StringBuilder stringBuilder2=new StringBuilder();
        while ((readCharInt=reader2.read())!=-1){
            stringBuilder2.append((char)readCharInt);
        }
        System.out.println(stringBuilder2.toString());
        reader2.close();
        //字节流
        FileOutputStream fileOutputStream=new FileOutputStream(new File("").getAbsolutePath()+"/io/test.txt");
        OutputStreamWriter outputStreamWriter=new OutputStreamWriter(fileOutputStream,"utf-8");
        outputStreamWriter.write("Hello，world！\n欢迎!!!\n");
        outputStreamWriter.append("另外一行内容");
        outputStreamWriter.flush();
        System.out.println("文件的编码为" + outputStreamWriter.getEncoding());
        outputStreamWriter.close();
        fileOutputStream.close();
        //字节流
        FileInputStream fileInputStream = new FileInputStream(new File("").getAbsolutePath()+"/io/test.txt");
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8"); // 使用 GBK 解码文件
        BufferedReader bufferedReader2 = new BufferedReader(inputStreamReader);
        String str;
        while ((str = bufferedReader2.readLine()) != null) {
            System.out.println(str);
        }
        bufferedReader2.close();
        inputStreamReader.close();
    }
}
